package net.csdn.business.webhook.listener;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.common.constant.CommonConstants;
import net.csdn.business.common.domain.request.webhook.WebhookNotifyDTO;
import net.csdn.business.common.domain.request.webhook.WebhookNotifyMessage;
import net.csdn.business.common.domain.vo.WebhookConfigVO;
import net.csdn.business.common.enums.WebHookEventTypeEnum;
import net.csdn.business.common.utils.JsonUtil;
import net.csdn.business.webhook.service.INotifyService;
import net.csdn.business.webhook.service.IWebhookConfigService;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.TreeMap;

/**
 * @ClassName AliProjectChangeMessageListener
 * @Description 项目变动mq通知
 * @Author zhangyl
 * @Date 2023/3/24 15:32
 */
@Slf4j
@Component
public class WebhookMessageListener implements MessageListener {

    @Autowired
    private INotifyService notifyService;

    @Autowired
    private IWebhookConfigService webhookConfigService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            String jsonMsg = new String(message.getBody(), StandardCharsets.UTF_8);
            log.info("---webhook tounotify，mq receive message：{}",jsonMsg);
            WebhookNotifyMessage webhookNotifyMessage = JSONObject.parseObject(jsonMsg, WebhookNotifyMessage.class);
            String webhookId=webhookNotifyMessage.getWebhookId();
            String eventType=webhookNotifyMessage.getEventType();
            String targetId=webhookNotifyMessage.getTargetId();
            String targetType=webhookNotifyMessage.getTargetType();
            String payload=webhookNotifyMessage.getPayload();
            log.info("---webhook notify：webhookId:{}",webhookId);
            //查询相关webhook配置是否存在
            WebhookConfigVO webhookConfigVO=webhookConfigService.selectWebhookConfigById(webhookId);
            if(webhookConfigVO!=null){
                Boolean isActive=webhookConfigVO.getIsActive();
                if(!WebHookEventTypeEnum.PING.getCode().equals(eventType)&&!isActive){
                    log.info("---webhook notify：webhookId:{} is not active, notify cancle",webhookId);
                    return Action.CommitMessage;
                }
                String notifyUrl=webhookConfigVO.getNotifyUrl();
                String secret=webhookConfigVO.getSecret();
                /** 请求体类型：1：application/json 2：application/x-www-form-urlencoded */
                Integer reqBodyType=webhookConfigVO.getReqBodyType();
                TreeMap<String, String> headerParams=new TreeMap<>();
                headerParams.put("Accept","*/*");
                headerParams.put("User-Agent","AtomGit-Hookshot");
                String deliveryId= IdUtil.fastUUID();
                headerParams.put("X-AtomGit-Delivery",deliveryId);
                headerParams.put("X-AtomGit-Event",eventType);
                headerParams.put("X-AtomGit-Hook-ID",webhookId);
                headerParams.put("X-AtomGit-Hook-Installation-Target-ID",targetId);
                headerParams.put("X-AtomGit-Hook-Installation-Target-Type",targetType);
                WebhookNotifyDTO notifyParams=new WebhookNotifyDTO();
                notifyParams.setWebhookId(webhookId);
                notifyParams.setPayload(payload);
                notifyParams.setEventType(eventType);
                notifyParams.setUrl(notifyUrl);
                notifyParams.setHeaderParams(headerParams);
                notifyParams.setDeliveryId(deliveryId);
                notifyParams.setSecret(secret);
                notifyParams.setReqBodyType(reqBodyType);
                switch (reqBodyType){
                    case 1:
                        headerParams.put("content-type","application/json");
                        break;
                    case 2:
                        headerParams.put("content-type","application/x-www-form-urlencoded");
                        break;
                }
                notifyService.sendNotify(notifyParams);
            }
        } catch (Exception e) {
            log.error("---webhook notify，consumer message error. msg:{} ex:{}", JsonUtil.toJsonString(message), JsonUtil.toJsonString(e));
            return Action.CommitMessage;
        } finally {
            MDC.remove(CommonConstants.TRACE_ID);
        }
        return Action.CommitMessage;
    }

}